package com.example.demo.controller.Document;

import com.example.demo.entity.Shop;
import com.example.demo.model.ResponseData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author hanqiang
 * @Classname QueryDocumentController
 * @Date 2020/10/6 13:53
 * @Description:
 */
@RestController
@RequestMapping("/document")
public class QueryDocumentController {

    @Autowired
    MongoTemplate mongoTemplate;

    private static final String COMMON_NAME="shops";

    @ApiOperation(value="查询所有数据",notes="查询数据")
    @GetMapping("findAll")
    public ResponseData findAll(){
        List<Shop> shoplist=mongoTemplate.findAll(Shop.class, COMMON_NAME);
        return ResponseData.success(shoplist);
    }

    @ApiOperation(value="查询一条数据",notes="查询数据")
    @GetMapping("/findOne")
    public ResponseData findOne(){
        Query query=new Query(Criteria.where("name").is("格尺"));
        Shop shop=mongoTemplate.findOne(query,Shop.class,COMMON_NAME);
        return ResponseData.success(shop);
    }

    @ApiOperation(value="通过id查询数据",notes="查询数据")
    @GetMapping("findById")
    public ResponseData findById(){
        String id="1";
        Shop shop=mongoTemplate.findById(id,Shop.class,COMMON_NAME);
        return ResponseData.success(shop);
    }

    @ApiOperation(value="统计数据数量",notes = "统计数量")
    @GetMapping("/count")
    public ResponseData count(){
        Query query=new Query(Criteria.where("type").is("学习用品"));
        long number=mongoTemplate.count(query,Shop.class,COMMON_NAME);
        return ResponseData.success(number);
    }

    @ApiOperation(value="集合中数据查询",notes = "查询数据")
    @GetMapping("/query")
    public ResponseData query() {
        Query query = Query.query(Criteria.where("name").is("铅笔").and("price").is(12));
        List<Shop> shopList = mongoTemplate.find(query, Shop.class,"shops");
        return ResponseData.success(shopList);
    }
}
